const net = require('net');

exports.barrier = function(ip) {
    let client = net.createConnection({
        host: ip,
        port: 8131
    });

    this.openCMD = function() {
        let bid = Math.floor(Math.random()*255).toString();
        let bodyObj = {"cmd":"ioctl_resp","id":bid,"delay":500,"io":0,"value":2};
        let body = JSON.stringify(bodyObj);
        
        let headerL = Buffer.from("VZ00");
        let headerR = Buffer.alloc(4);
        headerR.writeInt32BE( body.length );
    
        let cont = Buffer.concat([headerL , headerR , Buffer.from(body)]);
        return cont;
    }

    this.statusCMD = function() {
        let bid = Math.floor(Math.random()*255).toString();
        let bodyObj = {"cmd":"get_gpio_out_value","id":bid,"gpio":0};
        let body = JSON.stringify(bodyObj);
        
        let headerL = Buffer.from("VZ00");
        let headerR = Buffer.alloc(4);
        headerR.writeInt32BE( body.length );
    
        let cont = Buffer.concat([headerL , headerR , Buffer.from(body)]);
        return cont;
    }

    return new Promise(function(resolve,reject){

        client.on('error', err => {
            reject('服务器异常：', err);
        });

        client.on('connect', () => {
            // 向服务器发送数据
            if( !client.write(openCMD()) ) {
                reject('写入失败');
            }
        });

        client.on('data', buffer => {
            let rs = JSON.parse(buffer.slice(8).toString());
            client.end();
            if(rs.state_code==200) {
                resolve('success');
            } else {
                reject('开闸失败');
            }
        });

    })
}